package com.punai.costtool.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpMode;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.punai.common.core.domain.entity.SysPnDictionary;
import com.punai.common.exception.ServiceException;
import com.punai.common.utils.PnDictUtil;
import com.punai.common.utils.ServletUtils;
import com.punai.costtool.domain.entity.ToolMaintenance;
import com.punai.costtool.mapper.ToolMaintenanceMapper;
import com.punai.costtool.service.ToolMaintenanceService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

import static com.punai.costtool.constants.CostToolConstants.*;

@Service
public class ToolMaintenanceServiceImpl extends ServiceImpl<ToolMaintenanceMapper, ToolMaintenance> implements ToolMaintenanceService {

    @Override
    public void downloadFile(String id, HttpServletResponse response) throws IOException {
        ToolMaintenance one = this.getById(id);
        String fileName = one.getFileName();

        String fileDirectory = one.getFileDirectory();
        String ftpFileName = fileDirectory.substring(fileDirectory.lastIndexOf("/") + 1);
        String ftpFilePath = fileDirectory.substring(0, fileDirectory.lastIndexOf("/"));

        //设置文件输出类型
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment; filename="
                + new String(fileName.getBytes(StandardCharsets.UTF_8)));


        if (StrUtil.isEmpty(fileDirectory)) throw new ServiceException("成本编制工具版本未维护文件");
        Ftp ftp = getFtp();
        ftp.download(ftpFilePath, ftpFileName, response.getOutputStream());
        ftp.close();
    }

    @Override
    public boolean uploadFile(String id, MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (originalFilename.length() < 5 || !originalFilename.substring(originalFilename.length() - 4).equalsIgnoreCase(".exe")) {
            throw new ServiceException("请选择正确的文件格式");
        }
        try {
            ToolMaintenance one = this.getById(id);
            Ftp ftp = getFtp();

            String filePath = ftpPath + "/" + one.getId();
            String fileName = one.getId() + ".exe";

            if (StrUtil.isNotEmpty(one.getFileDirectory())) ftp.delFile(one.getFileDirectory());
            if (!ftp.exist(filePath)) ftp.mkDirs(filePath);
            ftp.cd(filePath);

            if (!ftp.upload(filePath, fileName, file.getInputStream())) {
                throw new ServiceException("上传到FTP文件服务失败!");
            }
            ftp.close();

            one.setFileName(originalFilename);
            one.setFileDirectory(filePath + "/" + fileName);
            this.saveOrUpdate(one);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
        return true;
    }

    private Ftp getFtp() {
        Ftp ftp;
        SysPnDictionary dictionary = PnDictUtil.getDictionary(userNameDic);
        if (StrUtil.equals(dictionary.getValue(), dictionary.getCode())) {
            ftp = new Ftp(PnDictUtil.getDictionary(ftpIPDic).getValue());
        } else {
            ftp = new Ftp(
                    PnDictUtil.getDictionary(ftpIPDic).getValue(),
                    Integer.parseInt(PnDictUtil.getDictionary(portDic).getValue()),
                    PnDictUtil.getDictionary(userNameDic).getValue(),
                    PnDictUtil.getDictionary(passWordDic).getValue());
        }
        String value = PnDictUtil.getDictionary(ftpModeDic).getValue();
        if (StrUtil.isNotEmpty(value)) {
            switch (value) {
                case "passive":
                    ftp.setMode(FtpMode.Passive);
                    break;
                case "active":
                default:
                    ftp.setMode(FtpMode.Active);
            }
        }
        return ftp;
    }

    protected String getFileName(String fileRealName) {
        try {
            HttpServletRequest request = ServletUtils.getRequest();
            String agent = request.getHeader("User-Agent");
            if (null != agent) {
                agent = agent.toLowerCase();
                if (agent.indexOf("firefox") != -1) {
                    fileRealName = new String(fileRealName.getBytes(), "iso8859-1");
                } else if (agent.indexOf("msie") != -1) {
                    fileRealName = java.net.URLEncoder.encode(fileRealName, "UTF-8");
                } else {
                    fileRealName = java.net.URLEncoder.encode(fileRealName, "UTF-8");
                }
            }
        } catch (UnsupportedEncodingException e) {
            return fileRealName;
        }
        return fileRealName;
    }
}
